<template>
  <div class="wrapper">
    <div class="login-container">
      <div class="login-title">登 录</div>
      <el-form :model="user" :rules="rules" ref="ruleForm">
        <el-form-item prop="username">
          <el-input size="medium" style="margin: 10px 0" placeholder="用户名" prefix-icon="el-icon-user"
                    v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="medium" style="margin: 10px 0" placeholder="密码" prefix-icon="el-icon-lock"
                    show-password
                    v-model="user.password"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 10px 0; text-align: right">
        <el-button type="primary" size="small" @click="login">登录</el-button>
        <el-button type="warning" size="small" @click="register">注册</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import userApi from "@/utils/Api/UserApi";
import {setRoutes} from '@/router/index'

export default {
  name: "Login",
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          // 验证规则,失去焦点进行校验，并且在输入的时候也进行校验
          {required: true, message: '请输入用户名', trigger: 'blur',},
          {trigger: 'change'}
        ],
        password: [
          // 验证规则,失去焦点进行校验，并且在输入的时候也进行校验
          {required: true, message: '请输入密码', trigger: 'blur'},
          {trigger: 'change'}
        ],
      }
    }
  },
  methods: {
    login() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          userApi.login(this.user).then(res => {
            if (res.code === 200) {
              localStorage.setItem("user", JSON.stringify(res.data.user))
              localStorage.setItem("token", res.data.token)
              this.$message.success("登录成功")
              this.$router.push('/home')

              // 设置动态路由
              setRoutes()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          this.$message.error("请输入账号/密码")
        }
      })
    },
    register() {
      this.$router.push('/register')
    }
  }
}
</script>

<style scoped>
.wrapper {
  /* 渐变的背景色   to bottom right ： 从左上角到右下角渐变 */
  background-image: linear-gradient(to bottom right, #FC466B, #3F5EFB);
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  margin: 200px auto;
  background-color: white;
  width: 350px;
  height: 250px;
  padding: 20px;
  border-radius: 10px;
}

.login-title {
  margin: 20px 0;
  font-size: 30px;
  font-weight: bold;
  text-align: center;
}

</style>